<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// 
//  user_model.php
//  www.6block.com
//  
//  Created by Will_Lee on 2011-05-21.
//  Copyright 2011 lishuzu. All rights reserved.
// 


class Work_model extends CI_Model
{
		function __construct(){
			parent::__construct();
			$this->load->helper('bbcode');
			$this->user = $this->session->userdata('user') ? $this->session->userdata('user') : '';
			$this->workstatus = array(
			 						'0'=>'未审核',
			 						'1'=>'已审核',
			 						'2'=>'推荐',
									'3'=>'删除',
			);
		}
		
		// 得到活动数据
		function get_works($num = '20', $offset = '', $uid='', $status = '', $order = 'dateline DESC', $where = array()){
			/********************查询数量********************/
			$data = $works = array();
			//查询数量
			if ($status) {
				// 0 未审核 1审核 2 推荐 3 删除
				$this->db->where('status', $status);
			}else{
				//不查询删除 和未审核的作品
				if ($uid != $this->user['uid']) {
					//如果是自己可以查询未审核作品
					$this->db->where('status !=', 0);
				}
				$this->db->where('status !=', 3);
			}
			
			if ($uid) {
				$this->db->where('uid =', $uid);
			}
			
			if ($where) {
				$this->db->where($where);
			}
			
			$data['count'] = $this->db->count_all_results('works');
			if (!$data['count']) {
				$data['count'] = '0';
				return $data['count'];
			}
			
			/********************查询数据********************/

			if ($status) {
				// 0 未审核 1审核 2 推荐 3 删除
				$this->db->where('status', $status);
			}else{
				//不查询删除 和未审核的作品
				if ($uid != $this->user['uid']) {
					//如果是自己可以查询未审核作品
					$this->db->where('status !=', 0);
				}
				$this->db->where('status !=', 3);
			}
			
			if ($uid) {
				$this->db->where('uid =', $uid);
			}
			
			if ($where) {
				$this->db->where($where);
			}
			
			$this->db->order_by($order);
			
			$query = $this->db->get("works", $num, $offset);	
					
			foreach ($query->result_array() as $row) {
				$row['avatar_small'] = avatar($row['uid'], 'small');
				
				$row['originimg'] = get_workimg($row['filepath'], 'origin', 'url');
				$row['bigimg'] = get_workimg($row['filepath'], 'big', 'url');
				$row['thumbimg'] = get_workimg($row['filepath'], 'thumb', 'url');
				
				$row['url'] = base_url().'work/index/'.$row['wid'];
				$row['key'] = get_workkey($row['wid']);
				$row['tags'] = empty($row['tag'])?array():unserialize($row['tag']);
				// 格式化描述
				$row['description'] = bbcode($row['description'], 2);
				//状态描述
				$row['workstatus'] = $this->workstatus[$row['status']] ? $this->workstatus[$row['status']] : '未知';
				$works[$row['wid']] = $row;
			}
			$data['works'] = $works;
			if ($data['works']) {
				return $data;
			}
			return false;
		}
		
		//作品详情
		function get_work($key, $value, $status = ''){
			if ($key) {
				$this->db->where($key, $value);
				if ($status) {
					// 0 未审核 1审核 2 推荐 3 删除
					$this->db->where('status', $status);
				}else{
					//不查询删除 和未审核的作品
					if ($key == 'uid' && $value != $this->user['uid']) {
						//如果是自己可以查询未审核作品
						$this->db->where('status !=', 0);
					}
					$this->db->where('status !=', 3);
				}

				$query = $this->db->get('works');
				$data = $query->row_array();
				if ($data) {
					$data['avatar_small'] = avatar($data['uid'], 'small');
					
					$data['originimg'] = get_workimg($data['filepath'], 'origin', 'url');
					$data['bigimg'] = get_workimg($data['filepath'], 'big', 'url');
					$data['thumbimg'] = get_workimg($data['filepath'], 'thumb', 'url');
					
					$data['url'] = base_url().'work/index/'.$data['wid'];
					$data['key'] = get_workkey($data['wid']);
					$data['tags'] = empty($data['tag'])?array():unserialize($data['tag']);
					// 格式化描述
					$data['description'] = bbcode($data['description'], 2);
					//状态描述
					$data['workstatus'] = $this->workstatus[$data['status']] ? $this->workstatus[$data['status']] : '未知';
					return $data;
				}
			}
			return false;
		}
		// 得到附加效果图
		public function getworkpic($wid){
			if ($wid) {
				$this->db->where('workid', $wid);
				$this->db->where('type', '1');
				$query = $this->db->get('pic');
				foreach ($query->result_array() as $row) {

					$row['originimg'] = get_workimg($row['filepath'], 'origin', 'url');
					$row['bigimg'] = get_workimg($row['filepath'], 'big', 'url');
					$row['thumbimg'] = get_workimg($row['filepath'], 'thumb', 'url');
					$row['url'] = base_url().'work/index/'.$row['workid'];
					$data[$row['picid']] = $row;
				}
				return $data;
			}
			return false;
		}
		
		
		function get_workfield($wid){
			if ($wid) {
				$this->db->where('wid', $wid);
				$query = $this->db->get('workfield');
				return $query->first_row('array');
			}
			return false;
		}
		function add($data){
			if ($data) {
				$this->db->insert('works', $data);
				return $this->db->insert_id();
			}
			return false;
		}
		
		function update($data){
			if ($data['wid']) {
				$wheresql = array('wid' => $data['wid']);
				$this->db->where($wheresql);
				unset($data['wid']);
				$this->db->update('works', $data);
				return true;
			}
			return false;
		}
		
		// 批量更新作品资料
		function updates($wids, $data){
			if ($wids) {
				foreach ($wids as $wid) {
					$this->db->where('wid', $wid);
					$work = $this->db->get('works')->row_array();
					if ($work['status'] == 3) {
						// 如果是已经删除状态 直接恢复 并加作品数量
						$this->db->query("UPDATE ".$this->db->dbprefix('user')." SET worknum = worknum + 1 WHERE uid='".$work['uid']."'");
					}
					$this->db->where('wid', $wid);
					$this->db->update('works', $data);;
				}

				return true;
			}
			return false;
		}
		
		//用户删除作品
		function remove($wid){
			if ($wid) {
				$this->db->where('wid', $wid);
				$query = $this->db->get('works');
				if ($value = $query->row_array()) {
					if ($value['status'] == "2") {
						showmessage('删除失败，作品已经被推荐。', 'worklist/index/'.$this->user['uid'], 2);
					}elseif ($value['status'] == "3") {
						showmessage('删除失败，作品已经删除。', 'worklist/index/'.$this->user['uid'], 2);
					}else{
						$this->db->where('wid', $wid);
						$this->db->update('works', array('status'=>'3'));
						$this->db->query("UPDATE ".$this->db->dbprefix('user')." SET worknum = worknum - 1 WHERE uid='".$value['uid']."'");
					return true;
					}
				}
				return false;
			}
			return false;
		}
		
		// 恢复用户删除
		function revert($wids){
			if ($wids) {
				$this->db->where_in('wid', $wids);
				$query = $this->db->get('works');
				foreach ($query->result_array() as $row) {
					if ($row['status'] == 3) {
						$this->db->where('wid', $row['wid']);
						$this->db->update('works', array('status'=>'0'));
						$this->db->query("UPDATE ".$this->db->dbprefix('user')." SET worknum = worknum + 1 WHERE uid='".$row['uid']."'");
					}
				}
			}
		}
		
		// 彻底删除 连同附件一起删除 还有相关评论
		function delete($wids){
			if ($wids) {
				$this->db->where_in('wid', $wids);
				$query = $this->db->get('works');
				foreach ($query->result_array() as $row) {
					$this->db->where('wid', $row['wid']);
					$this->db->delete('works');
					if ($row['status'] != 3) {
						//减少作品数量
						$this->db->query("UPDATE ".$this->db->dbprefix('user')." SET worknum = worknum - 1 WHERE uid='".$row['uid']."'");
					}
					// 删除评论
					$this->db->where('id', $row['wid']);
					$this->db->where('idtype', 'workid');
					$this->db->delete('comment');
					
					//删除feed
					$this->load->model('feed_model');
					$this->feed_model->delete_feed($row['wid'], 'workid');
					
					//删除附加效果图
					$this->load->model('pic_model');
					$pics = $this->getworkpic($row['wid']);
					
					if ($pics) {
						$picids = array_keys($pics);
						$this->pic_model->delete($picids);
					}
					
					// 删除主图片
					$originimg = FCPATH.'upload/attachments/'.get_workimg($row['filepath'], 'origin', 'path');
					$bigimg = FCPATH.'upload/attachments/'.get_workimg($row['filepath'], 'big', 'path');
					$thumbimg = FCPATH.'upload/attachments/'.get_workimg($row['filepath'], 'thumb', 'path');
					@unlink($originimg);
					@unlink($bigimg);
					@unlink($thumbimg);
				}
				return true;
			}
			return false;
		}
		// 上传设计图
		function upload_design($wid){
			if (!$this->user) {
				return false;
			}
			if (empty($wid)) {
				return false;
			}
			$workfield = $this->get_workfield($wid);
			
			$config =  array(
					'formname' => 'design',
					'upload_path' => FCPATH.'upload/designdrawings/',
					'allowed_types' => 'ai|psd|gif|jpg|png|jpeg',
					'overwrite' => true,
					'max_size' => '5000',
					'max_width' => '0',
					'max_height' => '0',
					'max_filename' => 0,
					'encrypt_name' => '',
					'remove_spaces' => TRUE,
				);
			if (!empty($workfield['design'])) {
				$pathinfo = pathinfo($workfield['design']);
				$config['file_name'] = $pathinfo['filename'];
				$config['upload_path'] = $config['upload_path'].$pathinfo['dirname'].'/';
				$result = upload_file($config, 1);
			}else{
				$config['file_name'] = 'design_'.$this->user['uid'].'_'.now().random(4);
				$result = upload_file($config);
			}

			if (!isset($result['error'])) {
				$this->db->query("REPLACE INTO ".$this->db->dbprefix('workfield')." (wid,design, design_type) VALUES ('".$wid."' ,'".$result['upload_data']['basename'].'/'.$result['upload_data']['file_name']."', '".$result['upload_data']['file_type']."')");	
			}
			return $result;
		}
		function upload_workimg($wid){
			if (!$this->user) {
				return false;
			}
			if (empty($wid)) {
				return false;
			}
			
			if ($wid && $_FILES['workpic']['name']) {
				$config = array();
				$config['file_name'] = $this->user['uid'].'_'.now().random(4);
				$config['max_width'] = 0;
				$config['max_height'] = 0;
				$config['max_size'] = '5000';
				$config['formname'] = 'workpic';
				$result = upload_file($config);
				if (isset($result['error'])) {
					showmessage('上传图片失败,'.$result['error'],'home/index', 3);				
				}else{
					$updatedata = array(
							'wid' => $wid,
							'filepath' => $result['upload_data']['basename'].'/'.$result['upload_data']['file_name'],
							'type' => $result['upload_data']['file_type'],
						);
					$result = $this->work_model->update($updatedata);
				}
				if ($updatedata) {
					$filepath = $updatedata['filepath'];
					$bigfile =  FCPATH.'upload/attachments/'.get_workimg($filepath, 'big', 'path');
					$thumbfile =  FCPATH.'upload/attachments/'.get_workimg($filepath, 'thumb', 'path');
					
					// 压缩图片
					$this->load->library('image_lib');
					$config['image_library'] = 'gd2';
					$config['source_image'] = FCPATH.'upload/attachments/'.$filepath;
					$config['maintain_ratio'] = TRUE;
					
					//大图 width 600
					$config['new_image'] = $bigfile;
					$config['width'] = 600;
					$config['height'] = 600;
					$this->image_lib->initialize($config);
					$res = $this->image_lib->resize();
					
					// 水印
					$water = array();
					$water['source_image'] = $bigfile;
					$water['wm_text'] = "@".$this->user['name']." ".base_url().'home/index/'.$this->user['uid'];
					$water['wm_type'] = 'text';
					$water['wm_font_path'] = './system/fonts/jjz.ttf';
					$water['wm_font_size'] = '8';
					$water['wm_font_color'] = '515151';
					$water['wm_vrt_alignment'] = 'bottom';
					$water['wm_hor_alignment'] = 'right';
					$water['wm_hor_offset'] = '0';
					$water['wm_vrt_offset'] = '0';
					$this->image_lib->initialize($water);
					$this->image_lib->watermark();
					
					// 小图 180*180
					$config['new_image'] = $thumbfile;
					$config['width'] = 180;
					$config['height'] = 180;
					$this->image_lib->initialize($config);
					$res = $this->image_lib->resize();
					
					//上传效果附图
					$this->load->model('pic_model');
					$this->pic_model->uploadpics($wid);
					
					return true;
				}else{
					return false;
				}
			}
		}
}
?>